import pprint
from datetime import datetime

from api.search.mapping_region import mapping_region

from api.search.schema_institution import Department
from task_utils.task_institution import task_accumulate_metric

from config import client, col_activity, col_register, col_alumni, col_institution

activity_col = col_activity
register_col = col_register
inst_col = col_institution
alumni_col = col_alumni

role_import = {"一般参与": 1, "中等参与": 2, "深度参与": 3}
acitvity_import = {"常规": 1, "重点": 2, "重大": 3}


def clean_region(region):
    if not region:
        return "", "", ""

    if region:
        province = region.get("province")
        city = region.get("city")
        district = region.get("district")
        return province, city, district


def region_map(region):
    if not region:
        return ""
    province = region.get("province")
    if not province:
        return ""
    for k, v in mapping_region.items():
        checker = [item for item in v if province.strip() in item]
        if checker:
            return k


def clean_media(media):
    data = []
    if not media:
        return []
    for med in media:
        data.append(med.get("path"))
    return data


def clean_dept(dept):
    if not isinstance(dept, list):
        dept = [dept]
    institutions = inst_col.find({"_id": {"$in": dept}}, {"institution_name": 1})
    data = []
    for inst in institutions:
        _kx = inst.get("level", -1)
        is_kx = True if _kx >= 0 else False
        data.append({"id": str(inst["_id"]), "institution_name": inst['institution_name'], "is_kexie": is_kx})
    return data


def import_department():
    for dept in inst_col.find({"is_deleted": {"$ne": True}}):
        inst_id = dept['_id']
        act_ids = activity_col.find({
            "$or": [{"institution_id": inst_id}, {"co_inst_ids": inst_id}],
            "is_deleted": {"$ne": True}}
        ).distinct('_id')

        person_counts = 0
        if act_ids:
            act_ids = act_ids
            person_counts = register_col.count_documents({"activity_id": {"$in": act_ids}, "is_attended": True})
        acc_activity, acc_alumni, acc_join,acc_institution = task_accumulate_metric(inst_id, True)

        department = Department(
            _id=str(inst_id),
            id=str(inst_id),
            institution_name=dept.get("institution_name"),
            in_kexie=dept.get("in_kexie", False),
            level=dept.get("level", -1),
            self_kexie=True if dept.get("level", -1) >= 0 else False,
            parent_institution_name=dept.get("parent_institution_name"),
            establishment_time=dept.get("establishment_time"),
            institution_type=dept.get("institution_type"),
            institution_location=dept.get("institution_location", ""),
            address=dept.get("region"),
            participants=person_counts,
            activities_of_participants=len(act_ids) if act_ids else 0,
            oindex=dept.get("oindex"),
            m_activity_overview=dept.get("m_activity_overview", []),  # 组织活动模块
            m_contact_overview=dept.get("m_contact_overview", []),  # 活动联系人才模块
            m_activity_span=dept.get("m_activity_span", []),  # 活动1-5年持续统计
            create_at=datetime.utcnow(),
            update_at=datetime.utcnow(),
            acc_join=acc_join,
            acc_alumni=acc_alumni,
            acc_institution=acc_institution,
            acc_activity=acc_activity,
        )
        print(department)
        department.save()


if __name__ == '__main__':
    import_department()
